<template>
  <el-drawer
    v-model="innerDrawer"
    title="流程查看"
    :append-to-body="true"
    size="80%"
    class="flow-view"
  >
    <el-col :span="16" :offset="4" >
      <div class="block">
        <el-timeline>
          <el-timeline-item
            v-for="(item,index ) in flowRecordList"
            :key="index"
            :icon="setIcon(item.finishTime)"
            :color="setColor(item.finishTime)"
          >
            <p style="font-weight: 700">{{item.taskName}}</p>
            <el-card :body-style="{ padding: '10px' }">
              <el-descriptions class="margin-top" :column="1" size="small" border>
                <el-descriptions-item v-if="item.assigneeName" label-class-name="my-label">
                  <template #label><i class="el-icon-user"></i>办理人</template>
                  {{item.assigneeName}}
                  <el-tag type="info" size="mini" v-if="item.deptName">{{item.deptName}}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item v-if="item.candidate" label-class-name="my-label">
                  <template #label><i class="el-icon-user"></i>候选办理</template>
                  {{item.candidate}}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-label">
                  <template #label><i class="el-icon-date"></i>接收时间</template>
                  {{item.createTime}}
                </el-descriptions-item>
                <el-descriptions-item v-if="item.finishTime" label-class-name="my-label">
                  <template #label><i class="el-icon-date"></i>处理时间</template>
                  {{item.finishTime}}
                </el-descriptions-item>
                <el-descriptions-item v-if="item.duration"  label-class-name="my-label">
                  <template #label><i class="el-icon-time"></i>耗时</template>
                  {{item.duration}}
                </el-descriptions-item>
                <el-descriptions-item v-if="item.comment" label-class-name="my-label">
                  <template #label><i class="el-icon-tickets"></i>处理意见</template>
                  {{item.comment.comment}}
                </el-descriptions-item>
                <el-descriptions-item v-if="item.comment && item.comment.hasOwnProperty('variables')" label-class-name="my-label">
                  <template #label><i class="el-icon-tickets"></i>历史问卷查看</template>
                  <el-button type="primary" @click="clickOpenJuan(item.comment.variables)">查看历史问卷</el-button>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-col>

    <el-drawer
      v-model="inputDrawerWenjuan"
      title="历史问卷查看"
      size="100%"
      class="baobiao-submit"
      :append-to-body="true"
    >
      <div style="display: flex;align-items: center;margin-top: 10px">
        <el-select v-model="wenjuanMode" placeholder="请选择问卷渲染方式"
                   @change="changeToggleMode" style="width: 200px">
          <el-option label="正常模式" value="normal"></el-option>
          <el-option label="表格模式" value="table"></el-option>
        </el-select>

        <div class="fixed-row" style="margin-left: 20px">
          <div><el-button type="primary" link @click="downloadPDF">导出PDF</el-button></div>
<!--          <div><el-button type="primary" link @click="downloadDOCX">导出DOCX</el-button></div>-->
        </div>
      </div>
      <WuJie name="liuchengStatementview" url="http://129.211.212.235:3005/"></WuJie>
    </el-drawer>
  </el-drawer>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import {flowRecord,flowShen,toggleMode} from '~/api/public'
  import {screenStore} from '~/stores/modules/screen'
  import {isClient} from '@vueuse/core'
  import {exportPDF2} from '~/api/public'
  // 动态导入jsPDF，避免SSR问题
  let jsPDF = null
  let Document = null
  let Packer = null
  let Paragraph = null
  let ImageRun = null
  let SectionType = null
  let saveAs = null
  if (isClient) {
    import('file-saver').then(module => {
      saveAs = module.saveAs
    }).catch(err => {
      console.error('Failed to load saveAs:', err)
    })
    import('jspdf').then(module => {
      jsPDF = module.default
    }).catch(err => {
      console.error('Failed to load jsPDF:', err)
    })
    import('docx').then(module => {
      Document = module.Document
      Packer = module.Packer
      Paragraph = module.Paragraph
      ImageRun = module.ImageRun
      SectionType = module.SectionType
    }).catch(err => {
      console.error('Failed to load jsPDF:', err)
    })
  }
  const props = defineProps({
    taskId:{
      type:String
    },
    deployId:{
      type:String,
    },
    procInsId:{
      type:String,
    },
    isType:{
      type:String,
      default:0
    },
    auditType:{
      type:String,
    },
    visitPlanId:{
      type:String,
    },
  })
  const screensStore = screenStore()
  const wenJson = ref('')
  const wenjuanMode = ref('normal')
  const inputDrawerWenjuan = ref(false)
  const innerDrawer = ref(false)
  const flowRecordList = ref([])
  const downloadDOCX = () => {
    window.document.querySelector("iframe[name=liuchengStatementview]").contentWindow.getDownloadPDF().then(async resImg => {
      const arrImg = [resImg]
      const { maxWidth, maxHeight } = await getMaxWidthHeight(arrImg)
      const arrData = []
      // 从top的位置开始加图片
      for (let i = 0; i < arrImg.length; i++) {
        const url = arrImg[i]
        const { width, height } = await getImgWidthHeight(url)
        arrData.push(new Paragraph({
          children: [
            new ImageRun({
              data: url,
              transformation: {
                width: width / 2.5,
                height: height / 2,
              },
            }),
          ],
        }))
      }
      const doc = new Document({
        sections: [
          {
            // type: SectionType.CONTINUOUS,
            // properties: {
            //   page: {
            //     size: {
            //       // 竖向A4: 210mm x 297mm
            //       width: maxWidth,
            //       height: maxHeight,
            //       unit: "twip" // 明确指定单位为twips
            //     },
            //     margin: {
            //       top: 20,
            //       right: 20,
            //       bottom: 20,
            //       left: 20,
            //       unit: "millimeter"
            //     },
            //     orientation: "portrait" // 竖向
            //   }
            // },
            children: [
              ...arrData
            ]
          }
        ]
      })

      // 生成并下载DOCX文件
      const blob = await Packer.toBlob(doc)
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '报表查看.docx'
      document.body.appendChild(a)
      a.click()

      // 清理
      setTimeout(() => {
        document.body.removeChild(a)
        URL.revokeObjectURL(url)
      }, 100)
    }).catch((e)=>{
      console.log(e,'e')
    })
  }
  const downloadPDF = () => {
    window.document.querySelector("iframe[name=liuchengStatementview]").contentWindow.getDownloadPDF().then(async resImg => {
      // 生成pdf
      // 第一个参数：l横向，p纵向
      // 第二个参数：计量单位: cm mm px等
      // 第三个参数：格式: 默认a4
      const arrImg = [resImg]
      exportPDF2({base64Images:arrImg}).then(res => {
        ElMessage.success('信息导出成功')
        saveAs(res, '问卷信息')
      })

    }).catch((e)=>{
      console.log(e,'e')
    })
  }
  function clickOpenJuan(wenjuanJson){
    wenJson.value = JSON.parse(wenjuanJson)
    inputDrawerWenjuan.value = true
    nextTick(()=>{
      if(window.document.querySelector("iframe[name=liuchengStatementview]").contentWindow.setWenJsonValue){
        setTimeout(()=>{
          window.document.querySelector("iframe[name=liuchengStatementview]").contentWindow.setWenJsonValue(wenJson.value,'yulan','yulan',screensStore.roles);
        },1000)
      }
      else{
        setTimeout(()=>{
          window.document.querySelector("iframe[name=liuchengStatementview]").contentWindow.setWenJsonValue(wenJson.value,'yulan','yulan',screensStore.roles);
        },1000)
      }
    })
  }
  async function getMaxWidthHeight(arr) {
    const widthList = []
    const heightList = []
    let maxHeight = 0
    let maxWidth = 0
    for (let i = 0; i < arr.length; i++) {
      const url = arr[i]
      const { width, height } = await getImgWidthHeight(url)
      widthList.push(width)
      heightList.push(height)
    }
    // 把数组变成升序然后倒过来取第一个就是拿最大宽度
    maxWidth = widthList.sort().reverse()[0]
    maxHeight = heightList.sort().reverse()[0]
    return {
      maxWidth,
      maxHeight,
    }
  }
  //获取图片宽高
  function getImgWidthHeight(src) {
    return new Promise((resolve, reject) => {
      const img = new Image()
      // 处理跨域图片问题
      img.crossOrigin = 'anonymous'
      img.src = src
      // 图片是否有缓存 如果有缓存可以直接拿 如果没有缓存 需要从onload拿
      if (img.complete) {
        const { width, height } = img
        resolve({
          width,
          height,
        })
      } else {
        img.onload = function () {
          const { width, height } = img
          resolve({
            width,
            height,
          })
        }
      }
    })
  }
  function openFlowDrawer(){
    innerDrawer.value = true
    flowRecordList.value = []
    nextTick(()=>{
      getFlowRecordList(props.procInsId,props.deployId)
    })
  }
  function changeToggleMode(){
    const data = {
      json:JSON.stringify(wenJson.value),
      type:wenjuanMode.value
    }
    toggleMode(data,'.baobiao-submit').then(res => {
      if(res.code == 200){
        ElMessage.success('问卷模式切换成功')
        setTimeout(()=>{
          window.document.querySelector("iframe[name=liuchengStatementview]").contentWindow.setWenJsonValue(JSON.parse(res.data),'yulan','yulan',screensStore.roles);
        },1000)
      }
    })
  }

  function getFlowRecordList(procInsId, deployId) {
    if(!props.isType){
      const params = {procInsId: procInsId, deployId: deployId}
      flowRecord(params).then(res => {
        flowRecordList.value = res.data.flowList;
      }).catch(res => {
        flowRecordList.value = []
      })
    }
    else{
      const params = {visitPlanId: props.visitPlanId, type: props.auditType}
      flowShen(params).then(res => {
        flowRecordList.value = res.data.flowList;
      }).catch(res => {
        flowRecordList.value = []
      })
    }

  }

  function setIcon(val) {
    if (val) {
      return "el-icon-check";
    } else {
      return "el-icon-time";
    }
  }
  function setColor(val) {
    if (val) {
      return "#2bc418";
    } else {
      return "#b3bdbb";
    }
  }
  defineExpose({
    openFlowDrawer
  })
</script>

<style scoped>

</style>
